<?php
// $Id: 

/**
 * @file
 * S-gas employee attendance administration and list UI.
 */

/*================= sg_employee_attendance admin functions===============*/
/*=========== general functions ==============*/

function _sg_employee_get_names_need_check_attendance(){
  $query ="SELECT n.*, e.eid as sg_employee_eid, e.name as sg_employee_ename
    FROM {node} n INNER JOIN {sg_employee} e ON n.vid = e.vid 
    WHERE e.check_attendance = 1 AND e.working = 1";
  $result = db_query($query, $eid, $from, $to);
  $employees = array();
  while($e = db_fetch_object($result)){
    $employees[$e->sg_employee_eid] = $e->sg_employee_ename;  
  };
  return $employees;
}


/*=========== drupal node_save functions ==============*/
function _sg_employee_attendance_generate_fields(&$node, $data){
  $node->sg_employee_eid = $data['eid'];
  $node->sg_employee_attendance_ddate = _sg_employee_date_mysql_to_drupal($data['date']);  //using the drupal_date array format
  $node->sg_employee_attendance_aid = $data['aid'];
  $node->sg_employee_attendance_duration = $data['duration'];
//  print_r($node);
}

function _sg_employee_create_attendance($data) {
    // Insert new data:
    $node->type = 'sg_attendance';
    require_once './modules/node/node.pages.inc';
    node_object_prepare($node);
    $node->uid = 1;

    $node->title = _sg_employee_get_name_by_eid($data['eid'])." ".$data['date']." ".$data['duration']." ".t('attendance');
    $node->body = '';
    $node->teaser = node_teaser($node->body);
    $node->filter = variable_get('filter_default_format', 1);
    $node->format = FILTER_FORMAT_DEFAULT;
    $node->language = '';
    $node->revision = 1;
    $node->promote = 0;
    $node->created = time();
    
    // Populate any sg_employee fields in the node
    _sg_employee_attendance_generate_fields($node, $data);

    // Save the node:
    node_save($node);
      
    unset($node);
}


function _sg_employee_create_attendance_records($days, $duration, $employees, $attendances){
  $num=0;
  foreach($days as $d){
    foreach($employees as $e){
      foreach($attendances as $a){
        $data = array( 'date'=>$d, 'duration'=>$duration, 'eid'=>$e, 'aid'=>$a);
        _sg_employee_create_attendance($data);
        $num++;
      }
    }
  }
  drupal_set_message(format_plural($num, '1 node created.', '@count nodes created.'));
}

/*
[days] => Array ( [6] => 6 [13] => 13 [22] => 22 [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [7] => 0 [8] => 0 [9] => 0 [10] => 0 [11] => 0 [12] => 0 [14] => 0 [15] => 0 [16] => 0 [17] => 0 [18] => 0 [19] => 0 [20] => 0 [21] => 0 [23] => 0 [24] => 0 [25] => 0 [26] => 0 [27] => 0 [28] => 0 [29] => 0 [30] => 0 [31] => 0 ) 
[year] => 2008 
[month] => 05 
[this_month] => 本月 
[names] => Array ( [3] => 3 [6] => 6 [4] => 0 [5] => 0 [7] => 0 [8] => 0 [10] => 0 [11] => 0 [15] => 0 [17] => 0 [20] => 0 [24] => 0 [35] => 0 [36] => 0 [37] => 0 [38] => 0 [40] => 0 [41] => 0 ) 
[situation] => Array ( [1010] => 1010 [1000] => 0 [1020] => 0 [1030] => 0 [1040] => 0 [1050] => 0 [2010] => 0 [2020] => 0 [3010] => 0 [3020] => 0 ) [duration] => 08:00:00 
 */

/*=========== form submit functions ==============*/
function sg_employee_create_attendance_create_submit($form, &$form_state){
  $days = array();
  $employees = array();
  $attendances = array();

  foreach($form_state['values']['days'] as $day){
    if($day != 0){
      $days[] = "".$form_state['values']['year'].'-'.$form_state['values']['month'].'-'.$day;
    }
  }

  $duration = $form_state['values']['duration'];

  foreach($form_state['values']['names'] as $eid){
    if($eid != 0){
      $employees[] = $eid;
    }
  }

  foreach($form_state['values']['situation'] as $sid){
    if($sid != '0' && $sid != '1000'){
      $attendances[] = $sid;
    }
  }
//  print_r($form_state['values']);die();
  _sg_employee_create_attendance_records($days, $duration, $employees, $attendances);
}

function sg_employee_create_attendance_filter_submit($form, &$form_state){
//  $session = &$_SESSION['sg_employee_create_attendances_filter'];
//  print_r($form_state['values']);
  if ($form_state['values']['op'] == t('This month')){
      $today = getdate();
      $month = $today[mon]; // month is the English name, mon is numerical
      $year = $today[year];
      $form_state['storage']['year'] = $year;
      $form_state['storage']['month'] = sprintf("%02d",$month);
  }
  elseif ($form_state['values']['op'] == t('<')){
      $date = _sg_employee_get_previous_month(array('year'=>$form_state['values']['year'], 'month'=>$form_state['values']['month']));
      $form_state['storage']['year'] = $date['year'];
      $form_state['storage']['month'] = $date['month'];
  }
  elseif ($form_state['values']['op'] == t('>')){
      $date = _sg_employee_get_next_month(array('year'=>$form_state['values']['year'], 'month'=>$form_state['values']['month']));
      $form_state['storage']['year'] = $date['year'];
      $form_state['storage']['month'] = $date['month'];
  }

  switch ($form_state['values']['op']) {
    case '':
      break;
  }
}

/*=========== form build functions ==============*/
/* 
 *  Entry function, called from sg_employee.module 
 */
function sg_employee_create_attendances_form($form_state){

  $form['date'] = _sg_employee_create_attendances_form_date($form_state);
  $form['employees'] = _sg_employee_create_attendances_form_employees($form_state);
  $form['attendance'] = _sg_employee_create_attendances_form_attendance($form_state);

  $form['create'] = array(
    '#type' => 'submit',
    '#value' => t('Create'),
    '#submit' => array('sg_employee_create_attendance_create_submit'),
  );

  $form['#theme'] = 'sg_employee_create_attendance';
  return $form;
}


function _sg_employee_create_attendances_form_date($form_state){
  $form['date'] = array(
    '#type' => 'fieldset',
    '#title' => t('Create attendance record(s) for the following date'),
  );

  $today = getdate();
  $year = $form_state['storage']['year'] ? $form_state['storage']['year'] : $today[year];
  $month = $form_state['storage']['month'] ? $form_state['storage']['month'] : sprintf("%02d", $today[mon]);

  $session = &$_SESSION['sg_employee_create_attendances_filter'];
  $session = is_array($session) ? $session : array();
  $session['year'] = $year;
  $session['month'] = $month;

  $lastday = _sg_employee_get_number_of_days_of_a_month($month,$year);
  $session['lastday'] = $lastday;

  $days = array();
  for($i = 1; $i <= $lastday; $i++){
    $days[$i] = $i;
  }
  $form['date']['days'] = array(
      '#type' => 'checkboxes',
      '#name' => 'sg_employee_attendance_date',
      '#options' => $days,
  );

  $form['date']['previous'] = array(
    '#type' => 'submit',
    '#value' => t('<'),
    '#submit' => array('sg_employee_create_attendance_filter_submit'),
    '#prefix' => '<div class="container-inline">',
  );

  $form['date']['year'] = array(
    '#type' => 'textfield',
    '#value' => $year,
    '#size' => 4,
    '#required' => TRUE,
  );
  
  $form['date']['month'] = array(
    '#type' => 'textfield',
    '#value' => $month,
    '#size' => 2,
    '#required' => TRUE,
  );


  $form['date']['next'] = array(
    '#type' => 'submit',
    '#value' => t('>'),
    '#submit' => array('sg_employee_create_attendance_filter_submit'),
  );

  $form['date']['this_month'] = array(
    '#type' => 'submit',
    '#value' => t('This month'),
    '#submit' => array('sg_employee_create_attendance_filter_submit'),
    '#suffix' => "</div>",
  );
  return $form['date'];
}

function _sg_employee_create_attendances_form_employees($form_state){
  $form['employees'] = array(
    '#type' => 'fieldset',
    '#title' => t('For the following employee(s)'),
  );

  $employees = _sg_employee_get_names_need_check_attendance(); //eid=>name
  $form['employees']['names'] = array(
      '#type' => 'checkboxes',
      '#name' => 'sg_employee_attendance_employee',
      '#options' => $employees,
  );

  return $form['employees'];
}

function _sg_employee_create_attendances_form_attendance($form_state){
  $form['attendance'] = array(
    '#type' => 'fieldset',
    '#title' => t('Create following record(s)'),
  );

  $form['attendance']['situation'] = array(
    '#type' => 'checkboxes',    
    '#name' => 'sg_employee_attendance_attendance',
    '#options' => _sg_employee_attendance_status(),
  );

  $form['attendance']['duration'] = array(
    '#type' => 'textfield',
    '#default_value' => '08:00:00',
    '#required' => TRUE,
  );

  return $form['attendance'];
}


/*=========== theme functions ==============*/
function theme_sg_employee_create_attendance($form) {
  $output .= _theme_sg_employee_create_attendance_date($form);
  drupal_render($form['date']); // escape the default fieldset render
  $output .= _theme_sg_employee_create_attendance_employees($form);
  drupal_render($form['employees']); // escape the default fieldset render
  $output .= _theme_sg_employee_create_attendance_attendance($form);
  drupal_render($form['attendance']); // escape the default fieldset render
  $output .= drupal_render($form);
  return $output;
}

function _theme_sg_employee_create_attendance_date($form){
//  print_r($form);
  $year = $_SESSION['sg_employee_create_attendances_filter']['year'];
  $month = $_SESSION['sg_employee_create_attendances_filter']['month'];
  $lastday = $_SESSION['sg_employee_create_attendances_filter']['lastday'];
  
//Days section
  $header[] = t('Sunday');
  $header[] = t('Monday');
  $header[] = t('Tuesday');
  $header[] = t('Wednesday');
  $header[] = t('Thursday');
  $header[] = t('Friday');
  $header[] = t('Saturday');
  $output = '';
  //render fieldset
  $element = $form['date'];
  if ($element['#collapsible']) {
    drupal_add_js('misc/collapse.js');

    if (!isset($element['#attributes']['class'])) {
      $element['#attributes']['class'] = '';
    }

    $element['#attributes']['class'] .= ' collapsible';
    if ($element['#collapsed']) {
      $element['#attributes']['class'] .= ' collapsed';
    }
  }

  $output .= '<fieldset'. drupal_attributes($element['#attributes']) .'>';
  $output .= ($element['#title'] ? '<legend>'. $element['#title'] .'</legend>' : '');
  $output .= (isset($element['#description']) && $element['#description'] ? '<div class="description">'. $element['#description'] .'</div>' : '') . $element['#value'];
  
  $output .= "<div>";
  $output .= drupal_render($element['previous']).drupal_render($element['year'])."-".drupal_render($element['month']).drupal_render($element['next'])." ".drupal_render($element['this_month']);
  $output .= "</div>";

  $date = getdate(strtotime($year."-".$month."-01"));
  $first_weekday = $date[wday];
//  print_r($form['date']);
  $first_week = true;
  $row = array();
  $day_of_month = 1;
  while($day_of_month<=$lastday){
    for($weekday = 0; ($weekday <= 6) && ($day_of_month<=$lastday); $weekday++){
      if ($first_week && ($weekday < $first_weekday)){
        $row[$weekday] = '_'; // the first blanks in a monthly calender
      }else{
        $row[$weekday] = drupal_render($form['date']['days'][$day_of_month]);
        $day_of_month++;
      }
    }
    if($day_of_month > $lastday){
      for(; $weekday <= 6; $weekday++){
        $row[$weekday] = '_'; // the last blanks in a monthly calender
      }
    }
    $rows[] = $row;
    $first_week = false;
  }
  $output .= theme('table', $header, $rows);
  $output .="</fieldset>\n"; //close fieldset
  
  return $output;
}

function _theme_sg_employee_create_attendance_employees($form){
  //render fieldset
  $element = $form['employees'];
  if ($element['#collapsible']) {
    drupal_add_js('misc/collapse.js');

    if (!isset($element['#attributes']['class'])) {
      $element['#attributes']['class'] = '';
    }

    $element['#attributes']['class'] .= ' collapsible';
    if ($element['#collapsed']) {
      $element['#attributes']['class'] .= ' collapsed';
    }
  }

  $output .= '<fieldset'. drupal_attributes($element['#attributes']) .'>';
  $output .= ($element['#title'] ? '<legend>'. $element['#title'] .'</legend>' : '');
  $output .= (isset($element['#description']) && $element['#description'] ? '<div class="description">'. $element['#description'] .'</div>' : '') . $element['#value'];

  $names_per_row = 5;
  $row = array();
  $rows = array();
  $k = 0;
  $total = 0;

  foreach($element['names'] as $e){
    if(isset($e['#title'])){
      $total++; 
    }
  }

  while($k < $total){
    for($j = 0; ($j < $names_per_row) && ($k < $total); $j++){
      $row[$j] = drupal_render($element['names'][$k]); 
      $k++;
    }
    $rows[] = $row;  
    $row = array();
  }
  for($j = 1; $j <= $names_per_row; $j++){
    $header[] = $j;
  }
  $output .= theme('table', $header, $rows);

  $output .="</fieldset>\n"; //close fieldset
  return $output;
}

function _theme_sg_employee_create_attendance_attendance($form){
  //render fieldset
  $element = $form['attendance'];
  if ($element['#collapsible']) {
    drupal_add_js('misc/collapse.js');

    if (!isset($element['#attributes']['class'])) {
      $element['#attributes']['class'] = '';
    }

    $element['#attributes']['class'] .= ' collapsible';
    if ($element['#collapsed']) {
      $element['#attributes']['class'] .= ' collapsed';
    }
  }

  $output .= '<fieldset'. drupal_attributes($element['#attributes']) .'>';
  $output .= ($element['#title'] ? '<legend>'. $element['#title'] .'</legend>' : '');
  $output .= (isset($element['#description']) && $element['#description'] ? '<div class="description">'. $element['#description'] .'</div>' : '') . $element['#value'];

  $per_row = 5;
  $row = array();
  $rows = array();
  $k = 0;
  $total = 0;
  $checkboxes = array();
  foreach($element['situation'] as $e){
    if($e['#type'] == 'checkbox' && isset($e['#title'])){
      $checkboxes[] = $e;
      $total++; 
    }
  }
  while($k < $total){
    for($j = 0; ($j < $per_row) && ($k < $total); $j++){
      $row[$j] = drupal_render($checkboxes[$k]); 
      $k++;
    }
    $rows[] = $row;  
    $row = array();
  }
  for($j = 1; $j <= $per_row; $j++){
    $header[] = $j;
  }

  $output .= theme('table', $header, $rows);
  $output .= drupal_render($element['duration']);
  $output .="</fieldset>\n"; //close fieldset
  return $output;
}


/*================= sg_employee_attendance admin functions end===============*/




/*================= sg_employee_attendance list functions===============*/

function sg_employee_attendance_list($form_state) {
  $form['filters'] = sg_employee_attendance_list_filter_form($form_state);
  $form['list'] = sg_employees_attendance_ui($form_state);
  return $form;
}

function _sg_employee_attendance_get_existing_periods(){
  $query = "SELECT DISTINCT(`to`) FROM {sg_salary} WHERE 1";
  $result = db_query($query);
  while ($row = db_fetch_object($result)) {
    $dates[$row->to] = $row->to;
  }
  return $dates;
}

function sg_employee_attendance_filters($form_state) {
  // Regular filters
  $form['date'] = array(
    '#type' => 'fieldset',
    '#title' => t('Create attendance record(s) for the following date'),
  );

  $today = getdate();
  $year = $form_state['storage']['year'] ? $form_state['storage']['year'] : $today[year];
  $month = $form_state['storage']['month'] ? $form_state['storage']['month'] : sprintf("%02d", $today[mon]);

  $lastday = _sg_employee_get_number_of_days_of_a_month($month,$year);
  
  $filters['date_year'] = array(
    'type' => 'textfield',
    'title' => t('Year'),
    'default_value' => $year,
  );

  $filters['date_month'] = array(
    'type' => 'textfield',
    'title' => t('Month'),
    'default_value' => $month,
  );

  $filters['working'] = array(
    'title' => t('Employee\'s working status in this company'),
    'options' => array(0=>t('Left'),1=>t('Working'), 2=>t('All')),
    'default_value' => $default_working_status,
  );


  return $filters;
}

function sg_employee_attendance_list_filter_form_submit($form, &$form_state){
  //$_SESSION['sg_employee_salary_list_filter'];
//      print_r($form_state);
  switch ($form_state['values']['submit']) {
    case t('Select'):
      $_SESSION['sg_employee_attendance_list_filter']['date_month'] = $form_state['values']['date_month'];
      $_SESSION['sg_employee_attendance_list_filter']['date_year'] = $form_state['values']['date_year'];
      $_SESSION['sg_employee_attendance_list_filter']['working'] = $form_state['values']['working'];
      break;
  }  
}

function sg_employee_attendance_list_filter_form($form_state){
  $session = &$_SESSION['sg_employee_attendance_list_filter'];
  $session = is_array($session) ? $session : array();
  $filters = sg_employee_attendance_filters($form_state);

  $form['filters'] = array(
    '#type' => 'fieldset',
    '#title' => t('Show only items where'),
  );
  $form['filters']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Select'),
    '#submit' => array('sg_employee_attendance_list_filter_form_submit'),
  );

  foreach ($filters as $key => $filter) {
    if($filter['type'] == 'textfield'){
      $form['filters']['option'][$key] = array( '#type' => 'textfield', 
                                                '#title' => $filter['title'], 
                                                '#default_value' => $filter['default_value'],
                                             );
    }else{
      $form['filters']['option'][$key] = array( '#type' => 'select', 
                                                '#title' => $filter['title'], 
                                                '#options' => $filter['options'],
                                                '#default_value' => $filter['default_value'],
                                              );
    }
  }
  return $form['filters'];
}

function sg_employees_attendance_ui($form_state){
  $session =$_SESSION['sg_employee_attendance_list_filter'];
  $session = is_array($session) ? $session : array();

  $filter['join'] = 'INNER JOIN {sg_attendance} a ON n.vid = a.vid INNER JOIN {sg_employee} e ON a.eid = e.eid ';
  $filter['where'] = "WHERE n.type = 'sg_attendance' ";
  $filter['args'] = array();

  if ($session['date_year']) {
    $filter['where'] .= "AND YEAR(a.date) = %d ";
    $filter['args'][] = $session['date_year'];
  }
  if ($session['date_month']) {
    $filter['where'] .= "AND MONTH(a.date) = %d ";
    $filter['args'][] = $session['date_month'];
  }
  if ($session['working']) {
    $filter['where'] .= "AND e.working = %d ";
    $filter['args'][] = $session['working'];
  }

  $query ='SELECT n.*, e.eid as sg_employee_eid, e.name as sg_employee_ename, a.aid as sg_employee_attendance_aid, a.duration as sg_employee_attendance_duration FROM {node} n '. $filter['join'] . $filter['where'] .' ORDER BY e.eid ASC';
  
  $result = pager_query(db_rewrite_sql($query), 50, 0, NULL, $filter['args']);
  $nodes = array();
  while ($node = db_fetch_object($result)) {
    $nodes[$node->nid] = '';
    $options = array();

  }
  $form['nodes'] = array('#type' => 'checkboxes', '#options' => $nodes);
  $form['pager'] = array('#value' => theme('pager', NULL, 50, 0));
  $form['#theme'] = 'sg_employee_attendance_nodes';
  return $form;
}

function theme_sg_employee_attendance_nodes($form) {

  // If there are rows in this form, then $form['sg_employee_eid'] contains a list of
  // the employee-id form elements.

  $header = array($select_header);
  
  $header[] = t('employee id');
  $header[] = t('employee name');
  $attendance_status = _sg_employee_attendance_status();
  foreach($attendance_status as $id=>$status_name){
    $header[] = $status_name;
  }
  $output = '';

  $rows[] = array(array('data' => t('No posts available.'), 'colspan' => '7'));

  $output .= theme('table', $header, $rows);
  if ($form['pager']['#value']) {
    $output .= drupal_render($form['pager']);
  }

  $output .= drupal_render($form);

  return $output;
}

/*================= sg_employee_attendance list functions end===============*/


